package jotunheim

import (
	"fmt"
	"os"

	"apiote.xyz/p/go-dirty"
)

type TyrConfig struct {
	ImapAddress          string
	ImapUsername         string
	ImapPassword         string
	ImapFolderInbox      string
	ImapFolderJunk       string
	ImapFolderArchive    string
	ImapFolderTrash      string
	ImapFolderDrafts     string
	ImapFolderQuarantine string
	ImapFolderSent       string
	RecipientDomain      string
	MainEmailAddress     string
}

type HermodrConfig struct {
	ImapAddress          string
	ImapUsername         string
	ImapPassword         string
	ImapFolderInbox      string
	ImapFolderRedirected string
	Recipient            string
	SmtpServer           string
	SmtpUsername         string
	PublicKey            string
}
type MimirConfig struct {
	ImapAddress       string
	ImapUsername      string
	ImapPassword      string
	ImapInbox         string
	RecipientTemplate string
	Categories        []string
	ForwardAddress    string
	PersonalAddress   string
	SmtpAddress       string
	SmtpSender        string
	Companion         string
}

type EostreConfig struct {
	ImapAddress       string
	ImapUsername      string
	ImapPassword      string
	DiaryImapAddress  string
	DiaryImapUsername string
	DiaryImapPassword string
	DiarySmtpAddress  string
	DiarySmtpUsername string
	DiarySmtpPassword string
	DiarySubject      string
	DiarySender       string
	DiaryRecipient    string
	AuthorisedSender  string
	PrivateKeyPass    string
	PrivateKey        string
	PublicKey         string
	DiaryPrivateKey   string
	DiaryPublicKey    string
}

type GersemiConfig struct {
	FireflyToken      string
	Firefly           string
	ImapAddress       string
	ImapUsername      string
	ImapPassword      string
	ImapInbox         string
	MessageMime       string
	DoneFolder        string
	DefaultSource     string
	WithdrawalRegexes []string
	DepositRegexes    []string
	Accounts          map[string]string
}

type Config struct {
	Tyr     TyrConfig
	Hermodr HermodrConfig
	Mimir   MimirConfig
	Eostre  EostreConfig
	Gersemi GersemiConfig
}

func Read(configPath string) (Config, error) {
	config := Config{}
	userConfigDir, err := os.UserConfigDir()
	if err != nil {
		return config, fmt.Errorf("while getting user config dir: %w", err)
	}
	possibleConfigs := []string{
		configPath,
		"/etc/asgard.dirty",
		userConfigDir + "/asgard.dirty",
		"asgard.dirty",
	}
	finalConfigPath := ""
	for _, possibleConfig := range possibleConfigs {
		_, err := os.Stat(possibleConfig)
		if err == nil {
			finalConfigPath = possibleConfig
			break
		}
	}
	if finalConfigPath == "" {
		return config, fmt.Errorf("no config found")
	}
	file, err := os.Open(finalConfigPath)
	if err != nil {
		return config, fmt.Errorf("while opening config: %w", err)
	}
	defer file.Close()
	err = dirty.LoadStruct(file, &config)
	return config, err
}
